<script setup lang="ts">
import { deleteOrderAPI, getOrderListAPI, getWeixinPayAPI, getWeixinPayTestAPI, putOrderReceiveByIdAPI } from '@/apis/order';
import { OrderItem, OrderListParams } from '@/types/order';
import { ref, toRaw } from 'vue';
import { ORDER_STATUS } from '@/constants/order';
import { onShow } from '@dcloudio/uni-app';

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();

const props = defineProps<{ orderState: number }>();

// 分页参数
const pageParams: Required<OrderListParams> = {
    page: 1,
    pageSize: 5,
    orderState: props.orderState,
};

// 获取订单列表
const orderList = ref<OrderItem[]>();

// 判断是否测试环境
const testing = import.meta.env.DEV;

// 订单支付事件
const onPay = async (orderId: string) => {
    if (testing) {
        // 测试版
        await getWeixinPayTestAPI({ orderId }).request;
    } else {
        // 上线版
        const response = await getWeixinPayAPI({ orderId }).request;
        await wx.requestPayment(response.result);
    }
    // 跳转到支付结果页面
    uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${orderId}` });
};

// 确认收货事件
const onReceive = (orderId: string) => {
    uni.showModal({
        content: '为保障您的权益，请在收到货物并确认无误后，再确认收货！',
        confirmText: '确认无误',
        success: async (success) => {
            if (success.confirm) {
                await putOrderReceiveByIdAPI(orderId).request;
                uni.showToast({ icon: 'none', title: '已确认收货，期待您的好评~' });
            }
        },
    });
};

// 删除订单事件
const onDelete = (orderId: string) => {
    uni.showModal({
        content: '是否删除此订单？',
        success: async (success) => {
            if (success.confirm) {
                await deleteOrderAPI({ ids: [orderId] }).request;
                uni.redirectTo({ url: '/pagesOrder/list/list?type=0', success: () => uni.showToast({ icon: 'success', title: '订单已删除~' }) });
            }
        },
    });
};

// 是否处于加载中
const loading = ref<UniApp.RequestTask | null>();

// 是否加载完成全部数据
let finish = false;

// 加载更多数据
const loadMore = async () => {
    // 判断是否有更多加载
    if (finish) return uni.showToast({ icon: 'none', title: '没有更多订单~' });
    if (!loading.value) {
        // 请求数据
        try {
            const { task, request } = getOrderListAPI(pageParams);
            loading.value = task;
            const response = await request;
            // 第一页为刷新，否则为加载
            if (pageParams.page === 1) orderList.value = response.result.items;
            else orderList.value?.push(...response.result.items);
            // 调整页数
            finish = pageParams.page >= response.result.pages;
            if (pageParams.page < response.result.pages) pageParams.page++;
        }
        finally {
            // 停止加载
            loading.value = null;
        }
    }
};

// 是否处于刷新中
const refreshing = ref(false);

// 刷新页面数据
const onRefresh = async () => {
    // 中断未完成的请求
    toRaw(loading.value)?.abort();
    loading.value = null;
    // 重置页数
    pageParams.page = 1;
    finish = false;
    // 发送请求
    refreshing.value = true;
    await loadMore();
    refreshing.value = false;
};

// 初始化数据
onShow(() => {
    if (!orderList.value) loadMore();
});

defineExpose({ loadMore });
</script>

<template>
    <!-- 订单列表 -->
    <scroll-view scroll-y class="orders" refresher-enabled :refresher-triggered="refreshing"
        @refresherrefresh="() => onRefresh()" @scrolltolower="() => loadMore()">
        <view class="card" v-for="order in orderList" :key="order.id">
            <!-- 订单信息 -->
            <view class="status">
                <text class="date">{{ order.createTime }}</text>
                <!-- 订单状态文字 -->
                <text>{{ ORDER_STATUS[order.orderState].text }}</text>
                <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
                <text class="icon-delete" @tap="onDelete" />
            </view>
            <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
            <navigator v-for="item in order.skus" :key="item.id" class="goods"
                :url="`/pagesOrder/detail/detail?id=${order.id}`" hover-class="none">
                <view class="cover">
                    <image mode="aspectFit" :src="item.image">
                    </image>
                </view>
                <view class="meta">
                    <view class="name ellipsis">{{ item.name }}</view>
                    <view class="type">{{ item.attrsText }}</view>
                </view>
            </navigator>
            <!-- 支付信息 -->
            <view class="payment">
                <text class="quantity">共{{ order.totalNum }}件商品</text>
                <text>实付</text>
                <text class="amount">
                    <text class="symbol">¥</text>{{ order.payMoney }}
                </text>
            </view>
            <!-- 订单操作按钮 -->
            <view class="action">
                <!-- 待付款状态：显示去支付按钮 -->
                <template v-if="order.orderState === 1">
                    <view class="button primary" @tap="onPay(order.id)">去支付</view>
                </template>
                <template v-else>
                    <navigator class="button secondary" :url="`/pagesOrder/create/create?orderId=${order.id}`"
                        hover-class="none">
                        再次购买
                    </navigator>
                    <!-- 待收货状态: 展示确认收货 -->
                    <view v-if="order.orderState === 3" class="button primary" @tap="onReceive(order.id)">确认收货</view>
                </template>
            </view>
        </view>
        <!-- 底部提示文字 -->
        <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
            <text v-if="!loading">--已经到底了--</text>
            <template v-else>
                <XtxLoadingIcon /><text>正在加载...</text>
            </template>
        </view>
    </scroll-view>
</template>

<style lang="scss">
.orders {
    width: 100%;
    height: 100%;

    .card {
        min-height: 100rpx;
        padding: 20rpx;
        margin: 20rpx 20rpx 0;
        border-radius: 10rpx;
        background-color: #fff;

        &:last-child {
            padding-bottom: 40rpx;
        }
    }

    .status {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 28rpx;
        color: #999;
        margin-bottom: 15rpx;

        .date {
            color: #666;
            flex: 1;
        }

        .primary {
            color: #ff9240;
        }

        .icon-delete {
            line-height: 1;
            margin-left: 10rpx;
            padding-left: 10rpx;
            border-left: 1rpx solid #e3e3e3;
        }
    }

    .goods {
        display: flex;
        margin-bottom: 20rpx;

        .cover {
            width: 170rpx;
            height: 170rpx;
            margin-right: 20rpx;
            border-radius: 10rpx;
            overflow: hidden;
            position: relative;
        }

        .quantity {
            position: absolute;
            bottom: 0;
            right: 0;
            line-height: 1;
            padding: 6rpx 4rpx 6rpx 8rpx;
            font-size: 24rpx;
            color: #fff;
            border-radius: 10rpx 0 0 0;
            background-color: rgba(0, 0, 0, 0.6);
        }

        .meta {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .name {
            height: 80rpx;
            font-size: 26rpx;
            color: #444;
        }

        .type {
            line-height: 1.8;
            padding: 0 15rpx;
            margin-top: 10rpx;
            font-size: 24rpx;
            align-self: flex-start;
            border-radius: 4rpx;
            color: #888;
            background-color: #f7f7f8;
        }

        .more {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22rpx;
            color: #333;
        }
    }

    .payment {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        line-height: 1;
        padding: 20rpx 0;
        text-align: right;
        color: #999;
        font-size: 28rpx;
        border-bottom: 1rpx solid #eee;

        .quantity {
            font-size: 24rpx;
            margin-right: 16rpx;
        }

        .amount {
            color: #444;
            margin-left: 6rpx;
        }

        .symbol {
            font-size: 20rpx;
        }
    }

    .action {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-top: 20rpx;

        .button {
            width: 180rpx;
            height: 60rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 20rpx;
            border-radius: 60rpx;
            border: 1rpx solid #ccc;
            font-size: 26rpx;
            color: #444;
        }

        .secondary {
            color: #27ba9b;
            border-color: #27ba9b;
        }

        .primary {
            color: #fff;
            background-color: #27ba9b;
        }
    }

    .loading-text {
        text-align: center;
        font-size: 28rpx;
        color: #666;
        padding: 20rpx 0;
        display: flex;
        justify-content: center;
    }
}
</style>